package com.divemotor.ventarepuestosinternet.security.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.divemotor.ventarepuestosinternet.dao.PerfilDAO;
import com.divemotor.ventarepuestosinternet.dao.UsuarioDAO;
import com.divemotor.ventarepuestosinternet.model.Perfil;
import com.divemotor.ventarepuestosinternet.model.Usuario;

@Service("userDetailsService")
@Transactional(readOnly=true)
public class UsuarioSecurityServiceImpl implements UserDetailsService ,Serializable{

	@Resource
	private UsuarioDAO usuarioDAO;
	@Resource
	private PerfilDAO perfilDAO;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
		User user = obtenerUserPorUsuarioLogin(username);
		if (user == null) {
			throw new UsernameNotFoundException("UserAccount for name \"" + username + "\" not found.");
		}
		
		return user;
	}
	
	private User obtenerUserPorUsuarioLogin(String usuario){
		User user 			   = null;
		Usuario usuarioRetorno = usuarioDAO.obtenerPorUsuarioLoginSistema(usuario);
		
		if(usuarioRetorno != null){
			user = new User(usuarioRetorno.getUsuario(), usuarioRetorno.getContrasenia(), true, true, true, true, transformarListaPerfilesAListaGrantedAuthority(usuarioRetorno.getListaPerfiles()));
		}
		
		return user;
	}
	
	private Collection<GrantedAuthority> transformarListaPerfilesAListaGrantedAuthority(List<Perfil> listaPerfiles){
		Collection<GrantedAuthority> listaGrantedAuthority= new ArrayList<GrantedAuthority>();	
		for (Perfil perfil : listaPerfiles) {
			SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(perfil.getCodigoPerfil());
			listaGrantedAuthority.add(grantedAuthority);
		}
		return listaGrantedAuthority;
	}

}
